import { TEChartOptions } from "@/models/reactiveComponent";
import { set } from "lodash-es";


export type TOptionsOperator = ReturnType<typeof optionsOperator>
export type TSeriesOperator = ReturnType<typeof seriesOperator>


export function createOptionsOperator(options: TEChartOptions) {

    let xAxis = [{}]
    let yAxis = [{}]

    if ('xAxis' in options && !Array.isArray(options.xAxis)) {
        options.xAxis = [options.xAxis]
    }
    if ('yAxis' in options && !Array.isArray(options.yAxis)) {
        options.yAxis = [options.yAxis]
    }

    xAxis = options.xAxis
    yAxis = options.yAxis


    function setProps(path: string, value: any) {
        set(options, path, value)
    }

    function setSeriesProps(seriesIdx: number, path: string, value: any) {
        setProps(`series[${seriesIdx}].${path}`, value)
    }

    function seriesHasData(seriesIdx: number) {
        if (seriesIdx >= options.series.length) {
            return false
        }

        const series = options.series[seriesIdx]
        return 'data' in series && (series.data as any[]).length > 0
    }

    return {
        options,
        setProps,
        setSeriesProps,
        seriesHasData,
    }

}

export function createSeriesOperator(series: TEChartOptions['series'][0]) {

    function setProps(path: string, value: any) {
        set(series, path, value)
    }

    function seriesHasData() {
        return 'data' in series && (series.data as any[]).length > 0
    }

    function getXAxisIndex() {
        if ('xAxisIndex' in series) {
            return series.xAxisIndex
        }

        return 0
    }

    function getYAxisIndex() {
        if ('yAxisIndex' in series) {
            return series.yAxisIndex
        }

        return 0
    }

    return {
        series,
        setProps,
        seriesHasData,
        getXAxisIndex,
        getYAxisIndex,
    }

}
